<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="脚本名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入脚本名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="rangedate"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增脚本</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 脚本列表 -->
    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="60" prop="number" />
      <el-table-column label="脚本名称" align="center" prop="name" />
      <el-table-column label="创建人" align="center" prop="creatorName" />
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="{ row }">
          <span>{{ parseTime(row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="{ row }">
          <el-button type="text" icon="View" @click="handleView(row)">查看脚本</el-button>
          <el-button type="text" icon="Edit" @click="handleUpdate(row)">修改</el-button>
          <el-button type="text" icon="Delete" @click="handleDelete(row)">删除</el-button>
          <el-button type="text" icon="video-play" @click="handleExecute(row)">执行脚本</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改脚本对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="formRef2" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="脚本名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入脚本名称" />
        </el-form-item>
        <el-form-item label="脚本内容">
        </el-form-item>
      </el-form>
      <ShEditor v-model="value" :readonly="readonly" :enableSnippets="true" />
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看脚本对话框 -->
    <el-dialog :title="title" v-model="lookOpen" width="700px" append-to-body>
      <ShEditor v-model="value" :readonly="true" />
    </el-dialog>

    <!-- 执行脚本选择主机对话框 -->
    <el-dialog :title="title" v-model="hostOpen" width="700px" append-to-body>
      <el-form
        :model="queryHostParams"
        ref="queryHostForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="主机名称" prop="name">
          <el-input
            v-model="queryHostParams.name"
            placeholder="请输入主机名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="主机地址" prop="hostname">
          <el-input
            v-model="queryHostParams.hostname"
            placeholder="请输入主机地址"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="hostListData" @selection-change="handleSelectionHostChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主机名称" align="center" prop="name" />
        <el-table-column label="主机地址" align="center" prop="hostname" />
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template #default="{ row }">
            <span>{{ parseTime(row.createTime) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitHostExecute">确 定</el-button>
        <el-button @click="hostCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance } from 'vue';
import { list, detail, del, add, put, run } from "@/api/script/script";
import { list as hostList } from "@/api/script/host";
import ShEditor from "@/components/common/ShEditor.vue";

const { proxy } = getCurrentInstance();
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  params: []
});

const queryHostParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  hostname: ''
});

const form = reactive({
  name: '',
  id: undefined
});
const postList = ref([]);
const hostListData = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const hostTotal = ref(0);
const open = ref(false);
const lookOpen = ref(false);
const hostOpen = ref(false);
const title = ref("");
const readonly = ref(false);
const value = ref('echo "hello shell"');
const scriptId = ref(0);
const ids = ref([]);
const hostIds = ref([]);
const rangedate = ref([]);
const rules = {
  name: [{ required: true, message: "脚本名称不能为空", trigger: "blur" }],
};

function getList() {
  loading.value = true;
  queryParams.startTime = rangedate.value[0];
  queryParams.endTime = rangedate.value[1];
  list(queryParams).then(response => {
    postList.value = (response.rows || []).map((item, index) => { item.number = index + 1; return item; });
    total.value = response.total;
    loading.value = false;
  });
};

function getHostList() {
  loading.value = true;
  hostList(queryHostParams).then(response => {
    hostListData.value = (response.rows || []).map((item, index) => { item.number = index + 1; return item; });
    hostTotal.value = response.total;
    loading.value = false;
  });
};

function handleQuery() {
  queryParams.pageNum = 1;
  getList();
};

function resetQuery(){
  rangedate.value = [];
  handleQuery();
};

function handleSelectionChange(selection){
  ids.value = selection.map(item => item.id).join(',');
};

function handleSelectionHostChange(selection) {
  hostIds.value = selection.map(item => item.id);
};

function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加脚本";
};

function handleUpdate(row){
  reset();
  const scriptId = row.id || ids.value;
  detail(scriptId).then(response => {
    form.name = response.data.name;
    form.id = response.data.id;
    readonly.value = false;
    value.value = response.data.content;

    open.value = true;
    title.value = "修改脚本";
  });
};

const handleView = (row) => {
  lookOpen.value = true;
  readonly.value = true;
  value.value = row.content;
  title.value = '查看脚本';
};

const handleExecute = (row) => {
  hostOpen.value = true;
  hostIds.value = [];
  title.value = '添加执行主机';
  scriptId.value = row.id;
  getHostList();
};

function submitForm (){
  form.content = value.value;
  proxy.$refs["formRef2"].validate((valid) => {
    if (valid) {
      if (form.id !== undefined) {
        put(form).then(() => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        add(form).then(() => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};

function submitHostExecute (){
  if (hostIds.value.length > 0) {
    loading.value = true;
    run({ scriptId: scriptId.value, hostIds: hostIds.value.join(',') })
      .then(() => {
        proxy.$modal.msgSuccess('执行成功');
        hostOpen.value = false;
        loading.value = false;
      });
  }
};

function handleDelete (row){
  const id = row.id || ids.value;
   proxy.$modal.confirm(`是否确认删除编号为"${id}"的数据项？`).then(() => {
    del(id).then(() => {
      getList();
      proxy.$modal.msgSuccess('删除成功');
    }).catch(() => {});
  });
};

function cancel() {
  open.value = false;
  reset();
};

function hostCancel() {
  hostOpen.value = false;
  reset();
};

function reset (){
  form.name = '';
  value.value = 'echo "hello shell"';
};

const parseTime = (time) => {
  return time ? new Date(time).toLocaleString() : '-';
};

getList();

</script>
